<?php

namespace App\Console\Commands;

use App\Jobs\LoginRobotJob;
use App\Model\BotsModel;
use App\Model\FromTradeDetailModel;
use App\Model\FromTradeModel;
use App\Service\LogService;
use Illuminate\Console\Command;

class SendFromTrade extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'send:fromtrade';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'send:fromtrade';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送存入报价';

    /**
     * SendFromOffer constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取当前机器上的机器人Id
     * @return array
     */
    protected function getBotIds()
    {
        return $botIds = BotsModel::where(['client_no'=>env('APP_NO')])->pluck('bot_id');
    }

    /**
     * 获取机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    protected function getBotsInfoBybotId($botId)
    {
        return BotsModel::getFromBotsInfoBybotId($botId);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $connection = (new FromTradeModel())->getConnection();
        $connection->beginTransaction();
        try {
            $botIds = $this->getBotIds();
            $fromTrade = FromTradeModel::whereIn('bot_id', $botIds)->where(['tradeoffer_status' => -1])->orderBy('from_trade_id', 'asc')->lockForUpdate()->first();

            if (empty($fromTrade)) {
                $connection->rollBack();
                echo "no find need send from offer " . PHP_EOL;
                exit();
            }

            $fromTradeId = $fromTrade['from_trade_id'];
            $botId = $fromTrade['bot_id'];
            $steamId = $fromTrade['steam_id'];
            $tradeToken = $fromTrade['tradeToken'];
            $tradeMsg = $fromTrade['tradeoffer'];

            if (time() - strtotime($fromTrade['created_at']) >= 300) {
                //创建报价超时
                FromTradeModel::where(['from_trade_id' => $fromTradeId])->update(['tradeoffer_status' => -100]);
                $connection->commit();
                echo "send from offer timeout fromTradeId : " . $fromTradeId . PHP_EOL;
                exit();
            }

            $bot = $this->getBotsInfoBybotId($botId);
            $steam = $bot['steam'];

            $tradeOffers = $steam->tradeOffers();
            $trade = $tradeOffers->createTrade($steamId);
            $user_from_trade_detail = FromTradeDetailModel::where(['from_trade_id' => $fromTradeId])->get();
            foreach ($user_from_trade_detail as $one) {
                $trade->addOtherItem($one['app_id'], 2, $one['o_id']);
            }
            $trade->setMessage($tradeMsg);

            echo "start send trade offer " . PHP_EOL;
            $tradeOfferId = $trade->sendWithToken($tradeToken);
            if ($tradeOfferId === 'relogin') {
                $currentQueue = 'LoginRobotJob_' . $bot['client_no'];
                dispatch((new LoginRobotJob($botId))->onQueue($currentQueue)->delay(1));
                echo "$botId is need logining " . PHP_EOL;
            } elseif ($tradeOfferId === 'full_package') {
                echo "你的物品背包已满 无法取回" . PHP_EOL;
            } elseif ($tradeOfferId === 'no_exist_item') {
                FromTradeModel::where(['from_trade_id' => $fromTradeId])->update(['tradeoffer_id' => 0, 'tradeoffer_status' => -2]);
                echo "物品可能已被您取回 fromTradeId : " . $fromTradeId . PHP_EOL;
            } elseif ($tradeOfferId === 'steam_no_response') {
                echo "steam 接口暂时不能响应 " . PHP_EOL;
            } elseif ($tradeOfferId === 'can_send_trade') {
                FromTradeModel::where(['from_trade_id' => $fromTradeId])->update(['tradeoffer_id' => 0, 'tradeoffer_status' => -3]);
                echo "您无法进行交易,将在邀请您交易时看到更多信息 fromTradeId : " . $fromTradeId . PHP_EOL;
            } elseif ($tradeOfferId === 'too_maney_trade') {
                echo " 请保证你的物品尽量不要分批次取出，导致发送报价过多，请先处理玩已发送的报价 " . PHP_EOL;
            } elseif ($tradeOfferId > 0) {
                echo 'send offer success' . $tradeOfferId . PHP_EOL;
                FromTradeModel::where(['from_trade_id' => $fromTradeId])->update(['tradeoffer_status' => FromTradeModel::$tradeOfferStatusMap['create'], 'tradeoffer_id' => $tradeOfferId]);
                echo "update offer fromTradeId : " . $fromTradeId . PHP_EOL;
            } else {
                echo "no anything return " . PHP_EOL;
            }

            $connection->commit();
            echo "end send trade offer " . PHP_EOL;
        } catch (\Exception $e) {
            echo $e->getMessage()  . PHP_EOL;
            LogService::getInstance()->addActionLog('work_from_error', 0, 0, $e->getMessage());
            $connection->rollBack();
            echo "create from offer error " . PHP_EOL;
        }
        exit;
    }
}